<template>
  <div>
    <el-row :gutter='20'>
      <el-col :span='12'>
        <el-card shadow='never'>
          <span>总人数：{{ usersCount }}</span>

          <el-card shadow='never'>
            <template #header>
              <div>
                添加部门
              </div>
            </template>
            <el-form ref='storeDepartFormRef' :model='form' label-width='120px' style='max-width: 460px'
                     status-icon>
              <el-form-item label='部门名称' prop='name' :rules="{ required: true, message: '不能为空',trigger: 'blur'}">
                <el-input v-model='form.name'  />
              </el-form-item>
              <el-form-item>
                <el-button type='primary' @click='onSubmit(storeDepartFormRef)'>提交</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          <el-table :data='tableData' border stripe style='width: 100%'>
            <el-table-column prop='id' label='ID' width='80' />
            <el-table-column prop='name' label='部门名称' />
            <el-table-column prop='users_count' label='员工数' width='80' />
            <el-table-column label='操作'>
              <template #default='{ row }'>
                <div>
                  <el-button-group>

                    <el-button type='primary' @click='edit(row)'>修改</el-button>
                    <el-button type='danger' @click='destroyDepartment(row)'>删除</el-button>
                    <el-button type='warning' @click='showUser(row)'>管理员工</el-button>
                  </el-button-group>
                </div>
              </template>
            </el-table-column>
          </el-table>

        </el-card>

        <el-dialog v-model='dialogVisible' title='修改部门' width='30%'>
          <el-form ref='updateDepartFormRef' :model='updateform' label-width='120px' style='max-width: 460px' status-icon>
            <el-form-item label='部门名称' prop='name' :rules="{ required: true, message: '不能为空',trigger: 'blur'}">
              <el-input v-model='updateform.name' />
            </el-form-item>
            <el-form-item>
              <el-button type='primary' @click='onSubmitDepartment(updateDepartFormRef)'>提交</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-col>

      <el-col :span='12'>

        <el-card shadow='never'>
          <template #header>
            <div>
              添加员工
            </div>
          </template>
          <el-form :inline='true' label-position='left' ref='storeUserFormRef' :model='storeuserForm'
                   class='demo-form-inline'>
            <el-form-item label='部门名称' prop='department_id' :rules="{ required: true, message: '部门不能为空',trigger: 'blur'}">
              <el-select v-model='storeuserForm.department_id' placeholder='Select'>
                <el-option v-for='(item, index) in departOpts' :key='index' :label='item.name'
                           :value='item.id' />
              </el-select>
            </el-form-item>
            <el-form-item label='名称' prop='name' :rules="{ required: true, message: '名称不能为空',trigger: 'blur'}">
              <el-input v-model='storeuserForm.name' />
            </el-form-item>
            <el-form-item label='手机号' prop='mobile' :rules="{ required: true, message: '手机号不能为空',trigger: 'blur'}">
              <el-input v-model='storeuserForm.mobile' />
            </el-form-item>

            <el-form-item>
              <el-button type='primary' @click='onSubmitStoreUser(storeUserFormRef)'>创建</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card shadow='never'>
          <p>部门：{{ currentDept?.name }}</p>
          <p>员工列表</p>
          <el-form ref='formRef' :inline='true' :model='searchField' label-width='80px'>
            <el-form-item label='用户名' prop='video_id'>
              <el-input v-model='searchField.name' />
            </el-form-item>
            <el-form-item>
              <el-button type='primary' @click='searchUser'>搜索</el-button>
              <el-button type='' @click='resetQuery'>重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :data='userData' border stripe style='width: 100%'>
            <el-table-column prop='id' label='ID' />
            <el-table-column prop='name' label='姓名'>
              <template #default='{ row }'>
                <div>
                  {{ row.name }}
                  <el-tag type='danger' v-if='row.departmanagerid.length>0'>管理员</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop='mobile' label='手机号账号' />
            <el-table-column label='操作' width='400'>
              <template #default='{ row }'>
                <div>
                  <el-button-group>
                    <el-button type='primary' @click='editUser(row)'>修改</el-button>
                    <el-button type='danger' @click='destoryUser(row.id)'>删除</el-button>
                    <el-button type='warning' @click='resetUserPassword(row)'>重置密码</el-button>
                    <el-button type='success' @click='bindManager(row)' v-if='row.departmanagerid.length<=0'>
                      设置管理员
                    </el-button>
                    <el-button type='danger' plain @click='unBindManager(row)' v-else>取消管理员</el-button>
                  </el-button-group>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination class='mt-3' :current-page='currentPage'
                         @current-change='handleCurrentChange' background :total='pageObj.total'
                         :page-size='pageObj.pageSize'
                         layout='total,prev, pager, next' />
        </el-card>

        <el-dialog v-model='dialogVisibleUser' title='修改员工' width='30%'>
          <el-form ref='updateUserFormRef' :model='userForm' label-width='120px' style='max-width: 460px' status-icon>
            <el-form-item label='部门' prop='department_id' :rules="{ required: true, message: '部门不能为空',trigger: 'blur'}" >
              <el-select v-model='userForm.department_id' placeholder='Select'>
                <el-option v-for='(item, index) in departOpts' :key='index' :label='item.name'
                           :value='item.id' />
              </el-select>
            </el-form-item>
            <el-form-item label='员工姓名' prop='name' :rules="{ required: true, message: '姓名不能为空',trigger: 'blur'}">
              <el-input v-model='userForm.name' />
            </el-form-item>
            <el-form-item label='手机号' prop='mobile' :rules="{ required: true, message: '手机号不能为空',trigger: 'blur'}">
              <el-input v-model='userForm.mobile' />
            </el-form-item>
            <el-form-item>
              <el-button type='primary' @click='onSubmitUpdateUser(updateUserFormRef)'>提交</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang='ts'>
import type { FormInstance } from 'element-plus'
import { ElMessageBox } from 'element-plus'

const dialogVisible = ref(false)
const currentDept = ref<DepartmentModel>({
  id: 0,
  name: '',
})
const { index, update, store, destory, deptUsers, setManager, unSetManager } = useDepartment()
const { update: updateUser, store: storeUser, resetPassword, deleteUser } = useUser()
const tableData = ref<DepartmentModel[]>([])
const form = ref<DepartmentModel>({
  id: 0,
  name: '',
})
const storeDepartFormRef = ref()
let updateform = ref<DepartmentModel>({
  id: 0,
  name: '',
})
//部门选项
const usersCount = ref(0)
const departOpts = ref<any>([])
const getData = async () => {
  const { departments, users_count } = await index()
  tableData.value = departments
  usersCount.value = users_count
  let opt = tableData.value.map(item => {
    return {
      name: item.name,
      id: item.id,
    }
  })
  departOpts.value = opt
}
// 设置管理员
const bindManager = async (user: any) => {
  const dept_id = currentDept.value.id
  const user_id = user.id
  await setManager(dept_id, user_id)
  const data = await deptUsers(currentDept.value.id, currentPage.value, searchField)
  userData.value = data.data
  pageObj.total = data.total
  pageObj.currentPage = data.current_page
  pageObj.pageSize = data.per_page
}

const unBindManager = async (user: any) => {
  const dept_id = currentDept.value.id
  const user_id = user.id
  await unSetManager(dept_id, user_id)
  const data = await deptUsers(currentDept.value.id, currentPage.value, searchField)
  userData.value = data.data
  pageObj.total = data.total
  pageObj.currentPage = data.current_page
  pageObj.pageSize = data.per_page
}
onMounted(() => {
  getData()
})
const destroyDepartment = async (row: DepartmentModel) => {
  // @ts-ignore
  if (row.users_count > 0) {
    ElMessageBox.alert('不允许删除，请移除员工后继续操作', '错误', {
      // if you want to disable its autofocus
      type: 'error',
      autofocus: false,
      confirmButtonText: '确定',
    })
    return
  }
  ElMessageBox.confirm(
    '确定删除吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    },
  )
    .then(async () => {
      const index = tableData.value.findIndex(item => item.id == row.id)
      tableData.value.splice(index, 1)
      await destory(row.id!)
      await getData()
    })
}
const edit = (row: DepartmentModel) => {
  dialogVisible.value = true
  updateform.value = row
}
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    console.log('formEl!')
    return
  }
  formEl.validate(async (valid, fields) => {
    if (valid) {
      await store(form.value).then(async () => {
        storeDepartFormRef.value.resetFields()
        await getData()
      })
    }
  })
}


const updateDepartFormRef =ref()
// 更新提交
const onSubmitDepartment = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    console.log('formEl!')
    return
  }
  formEl.validate(async (valid, fields) => {
    if (valid) {
      await update(updateform.value).then(async () => {
        updateDepartFormRef.value.resetFields()
        dialogVisible.value = false
        await getData()
      })
    }
  })

}
const searchField = reactive({
  name: '',
})
const currentPage = ref(1)
const pageObj = reactive({
  total: 0,
  pageSize: 0,
  pagerCount: 0,
  currentPage: 0,
})

const searchUser = async () => {
  const data = await deptUsers(currentDept.value.id, currentPage.value, searchField)
  userData.value = data.data
  pageObj.total = data.total
  pageObj.currentPage = data.current_page
  pageObj.pageSize = data.per_page
}

const resetQuery = async () => {
  searchField.name = ''
  await searchUser()
}
const handleCurrentChange = async (page: number) => {
  currentPage.value = page
  const data = await deptUsers(currentDept.value.id, currentPage.value, searchField)
  userData.value = data.data
  pageObj.total = data.total
  pageObj.currentPage = data.current_page
  pageObj.pageSize = data.per_page
}
// 员工
const showUser = async (row: DepartmentModel) => {
  currentDept.value = row
  const data = await deptUsers(row.id, currentPage.value, searchField)
  userData.value = data.data
  pageObj.total = data.total
  pageObj.currentPage = data.current_page
  pageObj.pageSize = data.per_page
}
const dialogVisibleUser = ref(false)
const userData = ref<UserModel[]>([])
const userForm = ref<UserModel>({
  department_id: '',
  name: '',
  mobile: '',
})
const storeuserForm = ref<UserModel>({
  department_id: '',
  name: '',
  mobile: '',
})
const editUser = (row: UserModel) => {
  dialogVisibleUser.value = true
  userForm.value = row
}
const destoryUser = async (id: number) => {
  ElMessageBox.confirm('确定删除吗?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  })
    .then(async () => {
      await deleteUser(id)
      await getData()
      await searchUser()
    })
}
const updateUserFormRef=ref()
const onSubmitUpdateUser = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    console.log('formEl!')
    return
  }
  formEl.validate(async (valid, fields) => {
    if (valid) {
      await updateUser(userForm.value)
      await searchUser()
      updateUserFormRef.value.resetFields()
      dialogVisibleUser.value=false
    }
  })
}
const storeUserFormRef=ref()
const onSubmitStoreUser = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    console.log('formEl!')
    return
  }
  formEl.validate(async (valid, fields) => {
    if (valid) {
      await storeUser(storeuserForm.value)
      await searchUser()
      storeUserFormRef.value.resetFields()
    }
  })
}
const resetUserPassword = async (row: any) => {
  await resetPassword(row.id)
}
</script>

<style lang='scss' scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}
</style>